import { ref, onUnmounted } from "vue";
import L, { type Map, type LatLngExpression } from "leaflet";
import "leaflet-animated-marker"; // 需要安装该依赖

// 路径动画配置项
export interface RouteAnimationOptions {
  /** 动画更新间隔(ms) */
  interval?: number;
  /** 车辆图标配置 */
  iconOptions?: L.IconOptions;
  /** 轨迹线样式 */
  polylineOptions?: L.PolylineOptions;
  /** 已行驶轨迹线样式 */
  realtimePolylineOptions?: L.PolylineOptions;
}

// 路径点数据类型
export interface RoutePoint {
  /** 纬度 */
  lat: number;
  /** 经度 */
  lng: number;
  /** 该路段速度系数 */
  speed?: number;
}

export function useRouteAnimation(
  map: Map,
  routePoints: RoutePoint[],
  options: RouteAnimationOptions = {}
) {
  // 状态管理
  const isPlaying = ref(false);
  const currentSpeed = ref(1);
  const animatedMarker = ref<any>(null);
  const routeLine = ref<L.Polyline | null>(null);
  const realtimeRouteLine = ref<L.Polyline | null>(null);
  const animationProgress = ref(0); // 动画进度(0-100)

  // 默认配置
  const defaultOptions = {
    interval: 200,
    iconOptions: {
      iconSize: [37, 26],
      iconAnchor: [19, 13],
      iconUrl: "/src/assets/car.png" // 使用项目中已有的car.png
    },
    polylineOptions: {
      weight: 8,
      color: "#3388ff"
    },
    realtimePolylineOptions: {
      weight: 8,
      color: "#FF9900"
    }
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 已行驶轨迹点数组
  const traveledPoints = ref<LatLngExpression[]>([]);

  // 初始化路径动画
  const init = () => {
    if (!map.value) return;

    // 提取经纬度坐标
    const latlngs = routePoints.map(
      point => [point.lat, point.lng] as LatLngExpression
    );
    // 提取速度数组
    const speedList = routePoints.map(point => point.speed || 1);

    // 创建完整路线轨迹线
    routeLine.value = L.polyline(latlngs, mergedOptions.polylineOptions).addTo(
      map.value
    );

    // 创建已行驶轨迹线
    realtimeRouteLine.value = L.polyline(
      [],
      mergedOptions.realtimePolylineOptions
    ).addTo(map.value);

    // 添加方向箭头
    addDirectionArrows();

    // 创建车辆标记
    createAnimatedMarker(latlngs, speedList);

    // 自动适应地图视角以显示完整路线
    map.value.fitBounds(routeLine.value.getBounds(), { padding: [50, 50] });
  };

  // 添加轨迹方向箭头
  const addDirectionArrows = () => {
    if (!map.value || !routeLine.value) return;
    // 需要引入leaflet.polylineDecorator插件
    L.polylineDecorator(routeLine.value, {
      patterns: [
        {
          repeat: 50,
          symbol: L.Symbol.arrowHead({
            pixelSize: 15,
            headAngle: 60,
            pathOptions: {
              color: "#ffffff",
              weight: 2,
              opacity: 0.8
            }
          })
        }
      ]
    }).addTo(map.value);
  };

  // 创建动态标记(车辆)
  const createAnimatedMarker = (
    latlngs: LatLngExpression[],
    speedList: number[]
  ) => {
    if (!map.value) return;

    const carIcon = L.icon(mergedOptions.iconOptions);

    // 使用animated-marker插件创建动态标记
    animatedMarker.value = L.animatedMarker(latlngs, {
      icon: carIcon,
      speedList: speedList,
      interval: mergedOptions.interval,
      playCall: updateTraveledRoute
    }).addTo(map.value);

    // 初始添加起点
    traveledPoints.value.push(latlngs[0]);
  };

  // 更新已行驶轨迹
  const updateTraveledRoute = (latlng: LatLngExpression) => {
    traveledPoints.value.push(latlng);
    realtimeRouteLine.value?.setLatLngs(traveledPoints.value);

    // 更新进度
    const totalPoints = routePoints.length;
    animationProgress.value = Math.round(
      (traveledPoints.value.length / totalPoints) * 100
    );
  };

  // 动画控制方法
  const start = () => {
    if (animatedMarker.value) {
      animatedMarker.value.start();
      isPlaying.value = true;
    }
  };

  const pause = () => {
    if (animatedMarker.value) {
      animatedMarker.value.pause();
      isPlaying.value = false;
    }
  };

  const stop = () => {
    if (animatedMarker.value) {
      animatedMarker.value.stop();
      isPlaying.value = false;
      animationProgress.value = 0;
      traveledPoints.value = [traveledPoints.value[0]]; // 保留起点
      realtimeRouteLine.value?.setLatLngs(traveledPoints.value);
    }
  };

  const speedUp = () => {
    if (animatedMarker.value) {
      currentSpeed.value *= 2;
      animatedMarker.value.setSpeetX(currentSpeed.value); // 注意原代码中的拼写错误: speetX应为speedX
    }
  };

  const speedDown = () => {
    if (animatedMarker.value) {
      currentSpeed.value /= 2;
      animatedMarker.value.setSpeetX(currentSpeed.value); // 注意原代码中的拼写错误
    }
  };

  // 清理方法
  const destroy = () => {
    stop();
    if (map.value) {
      routeLine.value?.remove();
      realtimeRouteLine.value?.remove();
      animatedMarker.value?.remove();
    }
  };

  // 组件卸载时自动清理
  onUnmounted(destroy);

  return {
    // 控制方法组
    controls: {
      init,
      start,
      pause,
      stop,
      speedUp,
      speedDown,
      destroy
    },
    // 状态数据组
    state: {
      isPlaying,
      animationProgress
    }
  };
}
